#include "console.h"
#include "debug_print.h"
#include "uart.h"
#include "loadrtu_runtime.h"
#include "soft_timer.h"

#ifdef BO_DEBUG

#define CONSOLE_BUF_SIZE 80

typedef struct CONSOLE_T
{
  CONSOLE_LINE_CB   cb;
  uint8             line_buf[CONSOLE_BUF_SIZE];
  uint8             char_count;
} CONSOLE_T;

CONSOLE_T s_console;

#define console_instance() &s_console

void console_init(CONSOLE_LINE_CB line_cb)
{
  CONSOLE_T* console = console_instance();
  console->cb = line_cb;
  console->char_count = 0;

  uart_init();
}

void console_on_char(uint8 c)
{
  CONSOLE_T* console = console_instance();

  // handle line buffer
  if (c == '\b')
  {
    if (console->char_count > 0)
    {
      debug_echo(c);
      console->char_count--;
    }
  }
  else if (c == '\r')
  {
    // we have received a whole line
    debug_echo(c);
    if (console->char_count >= CONSOLE_BUF_SIZE)
      console->char_count = CONSOLE_BUF_SIZE - 1;
    console->line_buf[console->char_count] = 0;
    console->cb(console->line_buf);
    console->char_count = 0;
  }
  else if (console->char_count < CONSOLE_BUF_SIZE)
  {
    debug_echo(c);
    console->line_buf[console->char_count++] = c;
  }
}

void console_check_uart()
{
  uint8 c;
  while (uart_getc(&c))
  {
    console_on_char(c);
  }
}

#endif // BO_DEBUG
